package com.kqb.sgpicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.kqb.sgpicturebackend.common.ErrorCode;
import com.kqb.sgpicturebackend.config.CosClientConfig;
import com.kqb.sgpicturebackend.exception.BusinessException;
import com.kqb.sgpicturebackend.model.bo.UploadPictureResult;
import com.kqb.sgpicturebackend.utils.ThrowUtils;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 杉果树皮
 * @date 2025/4/28 14:08
 * @description: 通用文件上传下载管理
 */
@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片到cos
     *
     * @param multipartFile
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        //校验文件参数
        validatePicture(multipartFile);
        //得到文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //得到文件后缀
        String suffix = FileUtil.getSuffix(originalFilename);

        String uuid = UUID.randomUUID().toString(true);

        String fileName = String.format("%s_%s.%s", DateUtil.format(new Date(System.currentTimeMillis()), "yyyyMMdd"), uuid, suffix);
        //文件路径
        String uploadFilePath = String.format("/%s/%s", uploadPathPrefix, fileName);

        File tempFile = null;
        try {
            tempFile = File.createTempFile(uploadFilePath, null);
            multipartFile.transferTo(tempFile);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadFilePath);
            uploadPictureResult.setName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(multipartFile.getSize());
            uploadPictureResult.setPicWidth(imageInfo.getWidth());
            uploadPictureResult.setPicHeight(imageInfo.getHeight());
            uploadPictureResult.setPicScale(NumberUtil.round(imageInfo.getWidth() * 1.0 / imageInfo.getHeight(), 2).doubleValue());
            uploadPictureResult.setPicFormat(imageInfo.getFormat());

            return uploadPictureResult;

        } catch (Exception e) {
            log.error("图片上传到储存桶失败:{}", uploadFilePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");

        } finally {
            if (tempFile != null) {
                boolean delete = tempFile.delete();
                if (!delete) {
                    log.error("临时文件删除失败:{}", uploadFilePath);
                }
            }
        }
    }

    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {

        //校验文件参数
//        validatePicture(multipartFile);
        validatePicture(fileUrl);
        //得到文件名
//        String originalFilename = multipartFile.getOriginalFilename();
        String originalFilename = FileUtil.mainName(fileUrl);
        //得到文件后缀

        String suffix = FileUtil.getSuffix(originalFilename);

        String uuid = UUID.randomUUID().toString(true);

        String fileName = String.format("%s_%s.%s", DateUtil.format(new Date(System.currentTimeMillis()), "yyyyMMdd"), uuid, suffix);
        //文件路径
        String uploadFilePath = String.format("/%s/%s", uploadPathPrefix, fileName);

        File tempFile = null;
        try {
            tempFile = File.createTempFile(uploadFilePath, null);

//               下载图片
//            multipartFile.transferTo(tempFile);
            HttpUtil.downloadFile(fileUrl, tempFile);

            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadFilePath);
            uploadPictureResult.setName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(tempFile));
            uploadPictureResult.setPicWidth(imageInfo.getWidth());
            uploadPictureResult.setPicHeight(imageInfo.getHeight());
            uploadPictureResult.setPicScale(NumberUtil.round(imageInfo.getWidth() * 1.0 / imageInfo.getHeight(), 2).doubleValue());
            uploadPictureResult.setPicFormat(imageInfo.getFormat());

            return uploadPictureResult;

        } catch (Exception e) {
            log.error("图片上传到储存桶失败:{}", uploadFilePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");

        } finally {
            if (tempFile != null) {
                boolean delete = tempFile.delete();
                if (!delete) {
                    log.error("临时文件删除失败:{}", uploadFilePath);
                }
            }
        }
    }

    private void validatePicture(String fileUrl) {
        ThrowUtils.throwNotIf(StrUtil.isBlank(fileUrl), new BusinessException(ErrorCode.PARAMS_ERROR, "图片路径为空"));
        // 1. 验证url格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式错误");
        }
        // 2. 校验url协议
        ThrowUtils.throwNotIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), new BusinessException(ErrorCode.PARAMS_ERROR, "文件协议错误"));
        // 3. 发送head请求验证文件是否存在
        try (HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4. 校验文件类型
            List<String> fileType = Arrays.asList("images/jpg", "images/jpeg", "images/png", "images/webp");
            String contentType = response.header("Content-Type");
            ThrowUtils.throwIf(!fileType.contains(contentType), new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误"));
            // 5. 校验文件大小
            String contentLengthStr = response.header("Content-Length");
            try {
                long contentLength = Long.parseLong(contentLengthStr);
                //文件大小
                final long maxSize = 1024 * 1024;
                ThrowUtils.throwIf(!(contentLength > maxSize * 2), new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件大小不能超过2MB"));
            } catch (NumberFormatException e) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "类型转换错误");
            }


        }


    }


    private void validatePicture(MultipartFile multipartFile) {
        //文件是否为空
        ThrowUtils.throwIf(multipartFile != null, new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件不能为空"));
        //文件大小
        final long maxSize = 1024 * 1024;
        ThrowUtils.throwIf(!(multipartFile.getSize() > maxSize * 2), new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件大小不能超过2MB"));

        //图片类型
        List<String> types = Arrays.asList("jpg", "jpeg", "png", "webp");
        ThrowUtils.throwIf(types.contains(FileUtil.getSuffix(multipartFile.getOriginalFilename())), new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件类型错误"));
    }


}
